package com.bobo.base.auth;

import com.bobo.base.R;
import com.bobo.base.logger.WebLogger;
import com.bobo.pojo.SysUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统认证控制器
 *
 * @author LILIBO
 * @since 2023-02-22
 */
@Tag(name = "系统认证控制器接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    /**
     * 登录认证
     */
    @Operation(summary = "登录认证")
    @WebLogger("登录认证")
    @PostMapping("/login")
    public R login(@RequestBody(required = false) SysUser sysUser) {
        // 完成登录验证，并发放Token（令牌）
        String token = authService.login(sysUser);
        return R.success(token);
    }

    /**
     * 令牌验证
     */
    @Operation(summary = "令牌验证")
    @WebLogger("令牌验证")
    @PostMapping("/verify")
    public R verify(@RequestBody String token) {
        // 解析Token进行验证，获取用户权限
        boolean flag = authService.verify(token);
        return R.success(flag);
    }

    /**
     * 退出登录
     */
    @Operation(summary = "退出登录")
    @WebLogger("退出登录")
    @PostMapping("/logout")
    public R logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser loginUser = (SecurityUser) authentication.getPrincipal();
        boolean logout = authService.logout(loginUser.getSysUser());
        return R.success(logout);
    }

}
